<?php

namespace App\Livewire;

use Livewire\Component;
use Yaroslam\SSH2\Session\ChainSession;
use Yaroslam\SSH2\Session\Connection\UserPasswordConnection;

class Scenario extends Component
{
    public $scenario;

    public function mount($ip, $connection)
    {
        $this->ip = $ip;
        $this->connection = $connection;
    }

    public function render()
    {
        return view('livewire.server.scenario', ['connection' => $this->connection, 'ip' => $this->ip]);
    }

    public function send()
    {
        $s = new ChainSession(new UserPasswordConnection(), ['port' => 22, 'host' => '194.87.110.114',
            'properties' => ['user' => 'root', 'password' => '3w3uxhXmmh']]);
        $s->initChain();
        $s = $this->generateSession(json_decode($this->scenario, true), $s);
        $s->apply();
        return;
//        $s = null;
    }

    private function generateSession($scenario, ChainSession $session)
    {
        foreach ($scenario as $s) {
            if ($s['type'] == 'exec') {
                $session->exec($s['command']);
            } elseif ($s['type'] == 'if') {
                $session->if($s['command'], $s['condition']);
                $session->then();
                $session = $this->generateSession($s['then'], $session);
                $session->endThen();

                $session->else();
                $session = $this->generateSession($s['else'], $session);
                $session->endElse();

                $session->endIf();
            } elseif ($s['type'] == 'for') {
                $session->for($s['start'], $s['stop'], $s['step']);
                $session = $this->generateSession($s['body'], $session);
                $session->endFor();
            }

        }

        return $session;
    }
}
